package main

import (
	"context"
	"fmt"
	"log"
	"regexp"
	"strings"

	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"

	"go.mongodb.org/mongo-driver/bson"
)

func main() {
	// Set up MongoDB client
	clientOptions := options.Client().ApplyURI("mongodb:dba_rw@eOPvu#qfaQVSdtH8//dds-0jl50b7f24292bf41952-pub.mongodb.rds.aliyuncs.com:3717")
	client, err := mongo.Connect(context.Background(), clientOptions)
	if err != nil {
		log.Fatal(err)
	}
	defer client.Disconnect(context.Background())

	// Access the database and collection
	db := client.Database("admin")
	col := db.Collection("$cmd.sys.inprog")

	// Construct the query
	filter := bson.D{
		{"active", true},
		{"secs_running", bson.D{{"$gte", 0}}},
	}

	// Execute the query
	cursor, err := col.Find(context.Background(), filter)
	if err != nil {
		log.Fatal(err)
	}
	defer cursor.Close(context.Background())

	// Iterate over the results
	for cursor.Next(context.Background()) {
		var item bson.M
		if err := cursor.Decode(&item); err != nil {
			log.Fatal(err)
		}

		// Filter out unwanted items
		desc, _ := item["desc"].(string)
		ns, _ := item["ns"].(string)
		if !shouldInclude(desc, ns) {
			continue
		}

		// Print relevant information
		fmt.Println("opid:", item["opid"], "|",
			"desc:", item["desc"], "|",
			"client:", item["client_s"], "|",
			"ns:", item["ns"], "|",
			"op:", item["op"], "|",
			"secs_running:", item["secs_running"], "|",
			"waitingForLock:", item["waitingForLock"], "|",
			"locks:", item["locks"], "|",
			"client:", item["client"], "\n",
			"query:", item["command"])
	}
	if err := cursor.Err(); err != nil {
		log.Fatal(err)
	}
}

// Function to determine whether an item should be included in the output
func shouldInclude(desc, ns string) bool {
	// Filter out items with specific descriptions and namespaces
	descFilters := []string{"ReplBatcher", "rsSync", "WT RecordStoreThread: local.oplog.rs"}
	nsFilters := []string{"local.*", "admin.*", "config.*"}

	for _, filter := range descFilters {
		if strings.Contains(desc, filter) {
			return false
		}
	}

	for _, filter := range nsFilters {
		match, _ := regexp.MatchString(filter, ns)
		if match {
			return false
		}
	}

	return true
}
